// 传参：methods请求方法，params参数，url接口，isFormData参数格式是否FormData，header请求头
import { apiURL } from './contant.js';

var api = async function(url, methods = 'get', params, isFormData = false, header = {
	token: uni.getStorageSync('token'),
}, timeout = 15000) {
	let newParams = {}
	//  判断参数是否是form-data
	if (params && isFormData) {
		newParams = new FormData()
		for (let i in params) {
			newParams.append(i, params[i])
		}
	} else {
		newParams = params
	}

	// 不同请求的判断  // 这里依据项目要求自行更改传参格式
	let response = {}; // 请求的返回值
	if (methods === 'put' || methods === 'post' || methods === 'patch') {
		try {
			response = await uni.request({
				method: methods,
				timeout: timeout,
				url: apiURL + url,
				data: newParams,
				header: header
			})
		} catch (err) {
			response = err
			uni.hideLoading()
		}
	} else if (methods === 'delete' || methods === 'get') {
		try {
			response = await uni.request({
				method: methods,
				timeout: timeout,
				url: apiURL + url,
				data: newParams,
				header: header
			})
		} catch (err) {
			response = err
			uni.hideLoading()
		}
	}
	
	// return response
	// response 这里直接return response的话,可以拿到返回的所有请求头数据,可以打印看看,然后根据自己项目需求进行判断
	// 有点麻烦的是这里的一串判断,因为没有拦截器
	// console.log(response)
	
		if (response.data.code == 0 || response.data.code == 200 || response.data.status_code == 0) {
			return response.data; // 返回响应值
		} else if (response.data.code == 401) {
			// uni.showToast({
			// 	icon:'none',
			// 	title:'登录失效，请重新登录'
			// });
			uni.clearStorageSync();
			return response.data;
		} else {
			uni.showToast({ // 显示接口返回msg
				title: response.data.msg || response.data.message || '接口返回错误',
				icon: 'none',
				duration: 1500
			});
			return response.data;
		}
}

export default api;
